<template>
  <!-- 这个组件是一个非渲染组件，主要通过JavaScript实现弹窗功能 -->
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as Cesium from 'cesium'

// 定义组件属性
const props = defineProps({
  position: {
    type: Array,
    required: true,
    validator: (value) => {
      return value.length === 3 && 
             typeof value[0] === 'number' && 
             typeof value[1] === 'number' && 
             typeof value[2] === 'number'
    }
  },
  html: {
    type: String,
    required: true
  },
  type: {
    type: String,
    default: 'interaction',
    validator: (value) => {
      return ['interaction', 'medium', 'update'].includes(value)
    }
  },
  options: {
    type: Object,
    default: () => ({})
  }
})

// 定义组件的暴露方法
const emit = defineEmits(['close', 'click'])

// 内部状态
const viewer = ref(null)
const popupContainer = ref(null)
const lineElement = ref(null)
const isAdded = ref(false)

// 默认配置 - 与标绘工具样式保持一致
const defaultOptions = {
  title: '自定义弹窗',
  showTitle: true,
  showClose: true,
  lineHeight: 80,    // 连接线长度
  lineWidth: 3,      // 连接线宽度
  lineColor: '#ff4d4f', // 标绘工具中的主题色
  popupAt: 'center', // left, center, right
  borderColor: 'rgba(255, 255, 255, 0.2)', // 浅色边框，与标绘工具一致
  backgroundColor: 'rgba(255, 255, 255, 0.1)', // 深色半透明背景，与标绘工具一致
  titleBackgroundColor: 'rgba(255, 255, 255, 0.15)', // 标题栏背景色
  textColor: 'rgba(255, 255, 255, 0.95)', // 白色文字，与标绘工具一致
  titleColor: 'rgba(255, 255, 255, 0.95)', // 标题文字颜色
  scale: 1.0,
  xyRatio: [320, 200], // 弹窗宽高比
  borderRadius: 6,      // 圆角半径，与标绘工具一致
  boxShadow: '0 4px 15px rgba(0, 0, 0, 0.25)', // 阴影效果
  contentPadding: '12px', // 内容区内边距
  lineBorderRadius: 2   // 连接线圆角
}

// 合并配置
const mergedOptions = { ...defaultOptions, ...props.options }

// 创建弹窗容器
const createPopupContainer = () => {
  // 创建连接线元素 - 与标绘工具样式保持一致
  lineElement.value = document.createElement('div')
  lineElement.value.className = 'custom-popup-line'
  lineElement.value.style.position = 'absolute'
  lineElement.value.style.background = mergedOptions.lineColor
  lineElement.value.style.width = `${mergedOptions.lineWidth}px`
  lineElement.value.style.pointerEvents = 'none'
  lineElement.value.style.transformOrigin = 'bottom center'
  lineElement.value.style.borderRadius = `${mergedOptions.lineBorderRadius}px`
  lineElement.value.style.opacity = '1'
  lineElement.value.style.boxShadow = '0 2px 6px rgba(0, 0, 0, 0.3)'
  lineElement.value.style.zIndex = '1000' // 确保在弹窗下层但可见
  
  // 创建弹窗容器 - 与标绘工具样式保持一致
  popupContainer.value = document.createElement('div')
  popupContainer.value.className = 'custom-popup-container'
  popupContainer.value.style.position = 'absolute'
  popupContainer.value.style.zIndex = '1001' // 弹窗z-index比连接线高1
  popupContainer.value.style.width = `${mergedOptions.xyRatio[0]}px`
  popupContainer.value.style.height = `${mergedOptions.xyRatio[1]}px`
  popupContainer.value.style.backgroundColor = mergedOptions.backgroundColor
  popupContainer.value.style.border = `1px solid ${mergedOptions.borderColor}` // 与标绘工具一致的边框
  popupContainer.value.style.borderRadius = `${mergedOptions.borderRadius}px`
  popupContainer.value.style.boxShadow = mergedOptions.boxShadow
  popupContainer.value.style.overflow = 'hidden'
  popupContainer.value.style.transform = `scale(${mergedOptions.scale})`
  popupContainer.value.style.transformOrigin = 'bottom center'
  popupContainer.value.style.display = 'flex'
  popupContainer.value.style.flexDirection = 'column'
  popupContainer.value.style.boxSizing = 'border-box'
  
  // 创建标题栏
  if (mergedOptions.showTitle) {
    const titleBar = document.createElement('div')
    titleBar.className = 'custom-popup-title-bar'
    titleBar.style.display = 'flex'
    titleBar.style.justifyContent = 'space-between'
    titleBar.style.alignItems = 'center'
    titleBar.style.padding = '8px 12px' // 与标绘工具一致的内边距
    titleBar.style.backgroundColor = mergedOptions.titleBackgroundColor
    titleBar.style.color = mergedOptions.titleColor
    titleBar.style.fontWeight = 'bold'
    titleBar.style.fontSize = '12px' // 与标绘工具一致的字体大小
    titleBar.style.borderTopLeftRadius = `${mergedOptions.borderRadius}px`
    titleBar.style.borderTopRightRadius = `${mergedOptions.borderRadius}px`
    titleBar.style.boxSizing = 'border-box'
    
    const titleText = document.createTextNode(mergedOptions.title)
    titleBar.appendChild(titleText)
    
    // 创建关闭按钮
    if (mergedOptions.showClose) {
      const closeButton = document.createElement('button')
      closeButton.className = 'custom-popup-close-btn'
      closeButton.style.background = 'transparent'
      closeButton.style.border = 'none'
      closeButton.style.color = 'white'
      closeButton.style.cursor = 'pointer'
      closeButton.style.fontSize = '14px'
      closeButton.style.padding = '0'
      closeButton.style.width = '20px'
      closeButton.style.height = '20px'
      closeButton.style.display = 'flex'
      closeButton.style.alignItems = 'center'
      closeButton.style.justifyContent = 'center'
      closeButton.textContent = '×'
      closeButton.style.borderRadius = '50%'
      closeButton.style.transition = 'all 0.2s ease'
      closeButton.style.userSelect = 'none'
      closeButton.onmouseenter = function() {
        this.style.backgroundColor = 'rgba(255, 77, 79, 0.8)'
      }
      closeButton.onmouseleave = function() {
        this.style.backgroundColor = 'transparent'
      }
      
      closeButton.addEventListener('click', () => {
        closePopup()
      })
      
      titleBar.appendChild(closeButton)
    }
    
    popupContainer.value.appendChild(titleBar)
  }
  
  // 创建内容容器 - 与标绘工具样式保持一致
  const contentContainer = document.createElement('div')
  contentContainer.className = 'custom-popup-content'
  contentContainer.style.flex = '1'
  contentContainer.style.overflow = 'auto'
  contentContainer.style.padding = mergedOptions.contentPadding
  contentContainer.style.color = mergedOptions.textColor
  contentContainer.style.fontSize = '11px' // 与标绘工具一致的字体大小
  contentContainer.style.lineHeight = '1.4'
  contentContainer.innerHTML = props.html
  contentContainer.style.boxSizing = 'border-box'
  contentContainer.style.zIndex = '1001'
  
  // 强制应用文字颜色样式
  contentContainer.style.color = mergedOptions.textColor
  contentContainer.style.setProperty('color', mergedOptions.textColor, 'important')
  
  // 优化滚动条样式
  contentContainer.style.scrollbarWidth = 'thin'
  contentContainer.style.scrollbarColor = `${mergedOptions.borderColor} transparent`
  
  // Webkit滚动条样式和确保文本颜色 - 与标绘工具样式保持一致
  const styleSheet = document.createElement('style')
  styleSheet.textContent = `
    // 与标绘工具一致的滚动条样式
    .custom-popup-content::-webkit-scrollbar {
      width: 6px;
    }
    .custom-popup-content::-webkit-scrollbar-track {
      background: rgba(255, 255, 255, 0.05);
      border-radius: 3px;
    }
    .custom-popup-content::-webkit-scrollbar-thumb {
      background: rgba(255, 255, 255, 0.2);
      border-radius: 3px;
    }
    .custom-popup-content::-webkit-scrollbar-thumb:hover {
      background: rgba(255, 255, 255, 0.3);
    }
    // 确保内容容器内的所有元素都应用文字颜色
    .custom-popup-content * {
      color: inherit !important;
      font-family: inherit;
      font-size: inherit;
    }
    // 与标绘工具一致的标题样式
    .custom-popup-content h3 {
      margin-top: 0;
      margin-bottom: 8px;
      font-size: 12px;
      font-weight: 600;
      color: rgba(255, 255, 255, 0.95);
    }
    // 与标绘工具一致的列表样式
    .custom-popup-content ul {
      margin: 8px 0;
      padding-left: 16px;
    }
    .custom-popup-content li {
      margin: 4px 0;
      font-size: 11px;
    }
    // 与标绘工具一致的按钮样式
    .custom-popup-content button {
      background: rgba(255, 255, 255, 0.08);
      border: 1px solid rgba(255, 255, 255, 0.15);
      border-radius: 4px;
      color: rgba(255, 255, 255, 0.95);
      padding: 4px 8px;
      font-size: 11px;
      cursor: pointer;
      transition: all 0.2s ease;
    }
    .custom-popup-content button:hover {
      background: rgba(255, 255, 255, 0.1);
      border-color: rgba(255, 255, 255, 0.2);
    }
  `
  document.head.appendChild(styleSheet)
  
  // 添加点击事件监听
  contentContainer.addEventListener('click', (e) => {
    emit('click', e)
  })
  
  popupContainer.value.appendChild(contentContainer)
  
  // 添加全局点击事件，实现点击弹窗外部不关闭
  document.addEventListener('click', (e) => {
    if (popupContainer.value && !popupContainer.value.contains(e.target) && 
        lineElement.value && !lineElement.value.contains(e.target)) {
      // 点击弹窗外部不做任何操作，保持弹窗打开
    }
  })
}

// 将弹窗添加到viewer
const addTo = (viewerInstance) => {
  if (isAdded.value || !viewerInstance) {
    return
  }
  
  viewer.value = viewerInstance
  
  // 创建弹窗元素
  createPopupContainer()
  
  // 添加到viewer的container
  if (viewer.value && viewer.value.container) {
    viewer.value.container.appendChild(lineElement.value)
    viewer.value.container.appendChild(popupContainer.value)
    
    // 添加渲染监听
    viewer.value.scene.preRender.addEventListener(updatePopupPosition)
    
    isAdded.value = true
    
    // 初始更新位置
    updatePopupPosition()
  }
}

// 更新弹窗位置
const updatePopupPosition = () => {
  if (!viewer.value || !popupContainer.value || !lineElement.value) {
    return
  }
  
  try {
    // 将经纬度转换为屏幕坐标 - 使用兼容当前Cesium版本的方法
    const cartesian3 = Cesium.Cartesian3.fromDegrees(props.position[0], props.position[1], props.position[2])
    
    // 在Cesium 1.133.0中，使用scene.cartesianToCanvasCoordinates方法
    let canvasPosition = viewer.value.scene.cartesianToCanvasCoordinates(cartesian3)
    
    // 如果上面的方法不存在，尝试使用另一种方式
    if (!canvasPosition) {
      // 创建一个临时的Billboard来获取屏幕坐标
      const billboard = new Cesium.BillboardCollection().add({
        position: cartesian3,
        show: false
      })
      canvasPosition = viewer.value.scene.cartesianToCanvasCoordinates(cartesian3)
      billboard.destroy()
    }
    
    if (canvasPosition) {
      // 更新连接线位置
      const lineHeight = mergedOptions.lineHeight
      const lineTop = canvasPosition.y-lineHeight
      const lineLeft = canvasPosition.x - mergedOptions.lineWidth / 2
      
      lineElement.value.style.top = `${lineTop}px`
      lineElement.value.style.left = `${lineLeft}px`
      lineElement.value.style.height = `${lineHeight}px`
      
      // 更新弹窗位置 - 修改计算逻辑，使弹窗与连接线顶部相连
      const popupWidth = mergedOptions.xyRatio[0] * mergedOptions.scale
      const popupHeight = mergedOptions.xyRatio[1] * mergedOptions.scale
      
      let popupLeft
      switch (mergedOptions.popupAt) {
        case 'left':
          popupLeft = canvasPosition.x - popupWidth - 10
          break
        case 'right':
          popupLeft = canvasPosition.x + 10
          break
        case 'center':
        default:
          popupLeft = canvasPosition.x - popupWidth / 2
          break
      }
      
      // 修改位置计算，使弹窗直接连接到连接线顶部
      const popupTop = lineTop - popupHeight
      
      popupContainer.value.style.top = `${popupTop}px`
      popupContainer.value.style.left = `${popupLeft}px`
    }
  } catch (error) {
    console.warn('Failed to update popup position:', error)
  }
}

// 更新弹窗内容
const updateHtml = (newHtml) => {
  if (!popupContainer.value) {
    return
  }
  
  const contentContainer = popupContainer.value.querySelector('.custom-popup-content')
  if (contentContainer) {
    contentContainer.innerHTML = newHtml
  }
}

// 更新弹窗位置坐标
const updatePosition = (newPosition) => {
  if (!Array.isArray(newPosition) || newPosition.length !== 3) {
    return
  }
  
  // 注意：在Vue 3中，props是只读的，我们不能直接修改props
  // 这里我们假设用户会通过v-bind更新position prop
  console.warn('Please update the position prop to change the popup location')
}

// 关闭弹窗
const closePopup = () => {
  destroy()
  emit('close')
}

// 销毁弹窗
const destroy = () => {
  if (!isAdded.value) {
    return
  }
  
  // 移除事件监听
  if (viewer.value && viewer.value.scene) {
    viewer.value.scene.preRender.removeEventListener(updatePopupPosition)
  }
  
  // 移除DOM元素
  if (popupContainer.value && popupContainer.value.parentNode) {
    popupContainer.value.parentNode.removeChild(popupContainer.value)
  }
  
  if (lineElement.value && lineElement.value.parentNode) {
    lineElement.value.parentNode.removeChild(lineElement.value)
  }
  
  popupContainer.value = null
  lineElement.value = null
  isAdded.value = false
}

// 暴露方法给父组件
const methods = {
  addTo,
  updateHtml,
  updatePosition,
  closePopup: () => emit('close'),
  onClickPopup: (callback) => {
    if (popupContainer.value) {
      const contentContainer = popupContainer.value.querySelector('.custom-popup-content')
      if (contentContainer) {
        contentContainer.addEventListener('click', callback)
      }
    }
  },
  onClosePopup: (callback) => {
    // 注册关闭回调
    emit('close', callback)
  },
  destroy
}

// 使用defineExpose暴露方法
defineExpose(methods)

// 组件卸载时清理
onBeforeUnmount(() => {
  destroy()
})
</script>

<style scoped>
/* 自定义滚动条样式 */
.custom-popup-content::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.custom-popup-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}

.custom-popup-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.custom-popup-content::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}
</style>